<template>
  <div class="main-content">
    <div class="top">
      <div class="top-op">
        <el-button type="danger" @click="batchDeleteFiles">
          <span class="iconfont icon-close"></span>
          批量取消分享
        </el-button>
        <div class="search-panel">
          <!-- input输入 -->
          <el-input v-model="searchName" clearable placeholder="搜索文件名" @keyup.enter="searchFiles">
            <template #suffix>
              <i class="iconfont icon-search" @click="searchFiles"></i>
            </template>
          </el-input>
        </div>
        <div class="iconfont icon-refresh" @click="refreshFileList"></div>
      </div>
      <div>{{ currentCategoryName }}文件 ({{ total }}个)</div>
    </div>

    <!-- 文件列表 -->
    <div class="file-list" v-if="fileList.length > 0">
      <el-table :data="fileList" style="width: 100%" @row-click="handleRowClick">
        <el-table-column width="50">
          <template #header>
            <el-checkbox v-model="isAllSelected" :indeterminate="isIndeterminate"
              @change="handleSelectAll"></el-checkbox>
          </template>
          <template #default="{ row }">
            <el-checkbox v-model="row.selected" @click.stop @change="updateSelectAllStatus"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="文件名" min-width="300">
          <template #default="{ row }">
            <div class="file-name-cell">
              <div class="file-icon">
                <img v-if="row.categoryId === 3" :src="row.imageUrl || getFileIcon(row)" alt="文件图标"
                  class="file-thumbnail">
                <img v-else :src="getFileIcon(row)" alt="文件图标" class="file-thumbnail">
              </div>
              <span class="file-name" :title="row.name" @click.stop="previewFileFunc(row)">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="过期时间" width="200">
          <template #default="{ row }">
            {{ formatDateTime(row.expireTime) }}
          </template>
        </el-table-column>
        <el-table-column label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <div class="file-actions">
              <el-tooltip content="复制分享链接" placement="top">
                <i class="iconfont icon-link action-icon" @click.stop="copyShareLink(row.id)"></i>
              </el-tooltip>
              <el-tooltip content="取消分享" placement="top">
                <i class="iconfont icon-close action-icon" @click.stop="cancelShare(row)"></i>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 无数据提示 -->
    <div v-else class="no-data">
      <div class="no-data-inner">
        <img src="@/assets/empty.png" alt="暂无数据" width="200">
        <div class="tips">暂无文件，快来分享吧</div>
      </div>
    </div>

    <!-- 重命名对话框 -->
    <el-dialog v-model="renameDialogVisible" title="重命名" width="30%">
      <el-input v-model="newFileName" placeholder="请输入新文件名"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRename">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文件预览组件 -->
    <Preview v-model:visible="previewDialogVisible" :file="currentPreviewFile" @download="downloadFile" />
  </div>
</template>

<script setup>
import Preview from "@/views/Preview.vue";
import { deleteRecycleFileService, shareListService, getImageService, restoreFileService, cancelShareService, getDownloadCodeService, downloadFileService } from "@/api/file.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, watch } from "vue";
import useClipboard from 'vue-clipboard3';
const { toClipboard } = useClipboard();
import { useRoute } from "vue-router";
import { useFileList } from "@/assets/js/file.list.js";

const route = useRoute();

// 使用通用文件列表逻辑
const {
  fileList,
  currentPage,
  pageSize,
  total,
  searchName,
  selectedFiles,
  isAllSelected,
  isIndeterminate,
  previewDialogVisible,
  currentPreviewFile,
  renameDialogVisible,
  newFileName,
  currentFile,
  currentCategory,
  currentCategoryName,
  getDefaultCoverByCategory,
  getFileIcon,
  formatFileSize,
  formatDateTime,
  loadFileList,
  handleSizeChange,
  handleCurrentChange,
  searchFiles,
  refreshFileList,
  updateSelectedFiles,
  updateSelectAllStatus,
  handleSelectAll,
  handleRowClick,
  previewFileFunc,
  downloadFile: baseDownloadFile,
  watchCategoryChange
} = useFileList({
  loadDataService: shareListService,
  categoryNames: {
    'all': '分享',
    'video': '视频',
    'music': '音频',
    'image': '图片',
    'doc': '文档',
    'zip': '压缩包',
    'others': '其他'
  }
});

// 监听路由变化
watchCategoryChange(watch);

// 下载文件
const downloadFile = async (file) => {
  await baseDownloadFile(file, downloadFileService);
};

// 复制分享链接
const copyShareLink = async (shareId) => {
  try {
    // 获取提取码
    const response = await getDownloadCodeService(shareId);
    const code = response.data;

    // 构建分享链接
    const shareUrl = window.location.origin + '/getShare/' + shareId;
    const copyText = `链接:${shareUrl} 提取码: ${code}`;

    // 复制到剪贴板
    await toClipboard(copyText);
    ElMessage.success('分享链接已复制');
  } catch (error) {
    ElMessage.error('复制失败');
    console.error('复制分享链接失败:', error);
  }
};

// 取消单个文件分享
const cancelShare = (file) => {
  ElMessageBox.confirm(
    `确定要取消文件 "${file.name}" 的分享吗？`,
    '取消分享确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await cancelShareService([file.id]);
      ElMessage.success('取消分享成功');
      loadFileList();
    } catch (error) {
      console.error('取消分享失败:', error);
      ElMessage.error('取消分享失败');
    }
  }).catch(() => {
    // 取消操作
  });
};

// 批量取消分享
const batchDeleteFiles = () => {
  // 再次确认选中的文件数量
  updateSelectedFiles();

  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请至少选择一个文件');
    return;
  }

  ElMessageBox.confirm(
    `确定要取消选中的 ${selectedFiles.value.length} 个文件的分享吗？`,
    '取消分享确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const fileIds = selectedFiles.value.map(file => file.id);
      await cancelShareService(fileIds);
      ElMessage.success('取消分享成功');
      loadFileList();
    } catch (error) {
      console.error('取消分享失败:', error);
      ElMessage.error('取消分享失败');
    }
  }).catch(() => {
    // 取消操作
  });
};

onMounted(() => {
  loadFileList();
});
</script>

<style lang="scss" scoped>
@use "@/assets/file.list.scss";

// Share.vue 特有样式</style>